package edu.maplef.bookwild.dao.impl.jdo;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;

import edu.maplef.bookwild.dao.IBaseDao;
import edu.maplef.bookwild.schema.Base;
import edu.maplef.bookwild.utils.PMF;

/**
 * Feb.22 2011, remove the DataCache mechanism from bookwild 
 * @author maple
 *
 * @param <T>
 */
public class BaseDaoJDOImpl<T extends Base> implements IBaseDao<T> {

	private Class<T> entityClass;

	protected PersistenceManager pm = null;

	//protected DataCache cache = null;

	protected Logger log = Logger.getLogger(this.getClass().getName());

	@SuppressWarnings("unchecked")
	public BaseDaoJDOImpl() {
		//cache = DataCache.getInstance();
		entityClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@Override
	public boolean removeById(String id) {
		//cache.delInCache(id);
		try {
			pm = PMF.get().getPersistenceManager();
			Object obj = pm.getObjectById(entityClass, id);
			pm.deletePersistent(obj);
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			pm.close();
		}
	}

	@Override
	public int removeByIds(String[] ids) throws Exception {
		int count = 0;
		for (String id : ids) {
			if (removeById(id))
				count++;
		}
		return count;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> list() {
		List<T> result = new ArrayList<T>();
		try {
			pm = PMF.get().getPersistenceManager();
			Extent extent = pm.getExtent(entityClass, false);
			for (Object t : extent) {
				result.add((T) t);
			}
			extent.closeAll();
			if (result.size() == 0)
				return null;
			return result;
		} catch (Exception e) {
			return null;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getById(String id) throws Exception {
		Base obj = null;
		//先从cache中获取数据，如果没有找到，从datastore中查找
		//obj = cache.findInCache(id);
		//if (obj != null)
		//return (T) obj;
		try {
			pm = PMF.get().getPersistenceManager();
			obj = (Base) pm.getObjectById(entityClass, id);
		} catch (Exception e) {
			//e.printStackTrace();
			return null;
		} finally {
			pm.close();
		}
		return (T) obj;
	}

	@Override
	public List<T> getByIds(String[] ids) throws Exception {
		List<T> result = new ArrayList<T>();
		if (ids.length == 0)
			return null;
		T obj;
		for (String s : ids) {
			obj = getById(s);
			if (obj != null)
				result.add(obj);
		}
		if (result.size() == 0)
			return null;
		return result;
	}

	@Override
	public String save(T t) throws Exception {
		pm = PMF.get().getPersistenceManager();
		try {
			//同时将数据存入datastore和memche
			//cache.putInCache(t.getId(), t);
			pm.makePersistent(t);
		} catch (Exception e) {
			//e.printStackTrace();
			return "";
		} finally {
			pm.close();
		}
		return t.getId();
	}
}